package cn.kgc.vue.redis;

import cn.kgc.vue.utils.ApplicationContextUtil;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author 课工场
 * @date 2024/10/9
 * @description
 */
public class RedisCache  implements Cache {

    private String id;

    public  RedisCache(String id){
        this.id = id;
    }
    @Override
    public String getId() {
        return this.id;
    }


    // 添加缓存
    @Override
    public void putObject(Object key, Object value) {
        RedisTemplate redisTemplate = getRedisTemplate();
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.put(id,key,value);
    }


    // 获取缓存
    @Override
    public Object getObject(Object key) {
        RedisTemplate redisTemplate = getRedisTemplate();
        HashOperations hashOperations = redisTemplate.opsForHash();
        Object o = hashOperations.get(id, key);
        return o;
    }

    @Override
    public Object removeObject(Object key) {
        return null;
    }

    // 清空缓存
    @Override
    public void clear() {
        RedisTemplate redisTemplate = getRedisTemplate();
        redisTemplate.delete(id);
    }

    @Override
    public int getSize() {
        return 0;
    }


    //  获取 redisTemplate对象
    public RedisTemplate getRedisTemplate() {

        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtil.getBean("redisTemplate");
        // 设置redis 中 key 和value的序列化方案
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}
